use axum::{
    async_trait,
    extract::FromRequestParts,
    http::{header::USER_AGENT, request::Parts, StatusCode},
};

pub struct ExtractUserAgent(pub Option<String>);

#[async_trait]
impl<S> FromRequestParts<S> for ExtractUserAgent
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        if let Some(user_agent) = parts.headers.get(USER_AGENT) {
            let agent = user_agent.to_str().ok().map(|s| s.to_owned());
            Ok(Self(agent))
        } else {
            Ok(Self(None))
        }
    }
}
